package cn.maihe.elg.operation.utils;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

public class OkHttpClientUtil {

    public static OkHttpClient createIgnoreVerifySSLOkHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
        // 创建一个信任所有证书的 TrustManager
        final X509TrustManager trustAllCerts = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {}

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {}

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };

        // 创建一个 SSLContext，并使用 TrustManager
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustAllCerts }, new java.security.SecureRandom());

        // 创建一个 OkHttpClient，并设置 SSLSocketFactory 和 HostnameVerifier
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(sslContext.getSocketFactory(), trustAllCerts)
                .hostnameVerifier((hostname, session) -> true) // 忽略主机名验证
                .connectionPool(new ConnectionPool(5, 300, TimeUnit.SECONDS))
                .build();

        return okHttpClient;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException {
        OkHttpClient okHttpClient = createIgnoreVerifySSLOkHttpClient();

        // 使用 okHttpClient 发送 HTTPS 请求
        // ...
    }
}
